package com.homestay.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求的URI
        String uri = request.getRequestURI();
        // 检查是否是登录页面或登录请求
        if("login".equals(request.getParameter("action"))||uri.contains("CodeServlet.do")){
            // 如果是登录页面或登录请求，直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 检查用户是否已登录
            Object user = request.getSession().getAttribute("nowUser");
            if (user != null) {
                // 用户已登录，继续处理请求
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                // 用户未登录，重定向到登录页面
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
